
var popup = {
	alert: function(text, onOk){
		this.show('系统提示', '<i class="fa fa-exclamation-triangle" aria-hidden="true"></i>' + text, {ok:function(){
			if(onOk && $.isFunction(onOk)){
				onOk.call(null);
			}
			$(this).fadeOut();
		}});
	},
	confirm: function(title, text, okFunc, onShow){
		this.show(title, text, {ok:function(){$(this).fadeOut(); okFunc.call(null)},cancel:function(){}});
	},
	showContent: function(title, text, okEvt, showEvt){
		this.show(title, text, {ok: okEvt || function(){},cancel: function(){}}, showEvt);
	},
	toast: function(content, funcOnFadeOut, showTime){
		var html = $('<div class="fr-col-3 fr-toast fr-hide">' + content + '</div>');
		$(html).appendTo('body');
		$(html).fadeIn(function(){
			// $(html).css({'display': 'inline-block'});
			showTime = showTime || 3000;
			setTimeout(function(){
				$(html).fadeOut(function(){
					$(html).remove();
					if(funcOnFadeOut && $.isFunction(funcOnFadeOut)){
						funcOnFadeOut.call(null);
					}
				});
			}, showTime);
		});
	},
	/**
		显示消息提示
		title:消息标题
		text:消息正文
		btn:需要显示的按钮，ok/cancel,json数组,如:[{ok: function(){}}]
		evt: 事件，json数据，包括beforeShow, afterShow
	**/
	show: function(title, text, btn, evt){
		var container = $('#mask');
		if(evt && evt.beforeShow != undefined && $.isFunction(evt.beforeShow)){
			evt.beforeShow.call(container);
		}
		container.fadeIn(function(){
			if(evt && evt.afterShow != undefined && $.isFunction(evt.afterShow)){
				evt.afterShow.call(container);
			}
		});
		$('.fr-row-title', container).text(title);
		$('.fr-popup-content', container).html(text);
		$('.fr-btn', container).hide();
		if(btn.ok != undefined && $.isFunction(btn.ok)){
			$('.fr-btn-orange', container).show();
			$('.fr-btn-orange', container).one('click', function(){
				if(btn.ok.call(container)){
					container.fadeOut();
				}
			})
		}
		if(btn.cancel && $.isFunction(btn.cancel)){
			$('.fr-btn-red', container).show();
			$('.fr-btn-red', container).one('click', function(){
				btn.cancel.call(container);
				container.fadeOut();
			})
		}
	}
}

var request = function(url, params, method, onSuccess, onFailed, onError, withAllReturn, options){
	if(method == 'get'){
		var query = "";
		for(var i in params){
			query += "&" + encodeURIComponent(i) + '=' + encodeURIComponent(params[i]);
		}
		url += url.indexOf('?') > -1 ? query : '?' + query.substr(1);
		params = {};
	}
	var params = {
		url: getUrl(url),
		data: method == 'post' ? JSON.stringify(params) : params || {},
		contentType: method == 'post' ? 'application/json; charset=utf-8' : 'application/x-www-form-urlencoded; charset=UTF-8',
		method: method,
		dataType: 'json',
		success: function(ret){
			if(withAllReturn){
				return onSuccess.call(null, ret);
			}
			if(ret && ret.retCode == 0){
				return onSuccess.call(null, ret.retData);
			}
			if(onFailed && $.isFunction(onFailed)){
				return onFailed.call(null, ret);
			}
			popup.toast(ret.retDescription || "请求服务器出错啦");
		},
		error:function(){
			if(onError && $.isFunction(onError)){
				return onError.call(null);
			}
			popup.toast('请求接口出错啦');
		}
	};
	if(options){

		for(var i in options){
			params[i] = options[i];
		}
	}
	return $.ajax(params);
}

var xhrUpload = function(url, file, onProgress, onSuccess, onFail){
	if(!window.FileReader || !XMLHttpRequest){
		return popup.toast('您的浏览器版本太低，请升级。推荐使用谷歌浏览器');
	}
	var fr = new FileReader();
	fr.onload = function(){
		var xhr = new XMLHttpRequest();
		xhr.upload.onprogress = function(e){
			console.log(111);
			if(onProgress && $.isFunction(onProgress)){
				return onProgress.call(null, e);
			}
		}
		xhr.onreadystatechange = function(){
			if(this.readyState == 4){
				if(this.status == 200){
					return $.isFunction(onSuccess) && onSuccess.call(this, this.responseText);
				}else{
					return $.isFunction(onFail) && onFail.call(this, this.responseText);
				}
			}
		}
		xhr.open("post", getUrl(url), true);
		xhr.send(this.result);
	}
	fr.readAsArrayBuffer(file);
}

var cookie = {
	set: function(key, val){
		document.cookie = escape(key) + '=' + escape(val);
	},
	get: function(key){
		var _cookie = document.cookie;
		var _cookies = _cookie.split(';');
		for(var i in _cookies){
			var pairs = _cookies[i].split('=');
			if(unescape(pairs[0]) == key){
				return unescape(1);
			}
		}
	}
}

function getUrl(url){
	return url; 
	// return '/cgi' + url.replace('.', '-');
}

var initialize = function(){
	var status_bar = $('#status_bar');
	if(status_bar.size() == 0){
		return;
	}
	var ip       = sessionStorage.getItem('ip') || '';
	var username = sessionStorage.getItem('username') || '';
	$('#status_ip', status_bar).text('IP:' + ip);
	$('#status_username', status_bar).text('User:' + username);

	var getTimeString = function(){
		var d        = new Date();
		return d.getFullYear() + '-' + zeroPad(d.getMonth() + 1) + '-' + zeroPad(d.getDate()) + ' ' + zeroPad(d.getHours()) + ':' + zeroPad(d.getMinutes()) + ':' + zeroPad(d.getSeconds());
	}
	var setTimeText = function(){
		var time = getTimeString();
		$('#status_time', status_bar).text('Time:' + time);
		setTimeout(setTimeText, 1000);
	}
	var zeroPad = function(str){
		var pad_char = str <= 9 ? '0' : '';
		return pad_char + str;
	}

	var ping = function(){
		var req  = request('/heartBeat.cgi', {index:0}, 'get', function(data){
			// $('#status_ip').html('IP:' + data.ip);
			$('#status_text').html('Online');
			$('#status_bar>span:eq(1)>i').removeClass('fa-offline').addClass('fa-online');
		}, function(){

		}, function(){

		}, false, {
			timeout: 10000, 
			complete: function (XMLHttpRequest,status) {
                setTimeout(function(){
                	ping();
                }, 1000);
                if(status == 'timeout') {
                    req.abort();    // 超时后中断请求
                    $('#status_text').html('Offline');
                    $('#status_bar>span:eq(1)>i').removeClass('fa-online').addClass('fa-offline');
                    return;
                }
        }});
	}

	ping();
	setTimeText();
}

var lighter = function(){
	var stop = false;
	this.timer = null;
	this.getColor = function(color){
		var colorCls = 'fr-bg-white';
		if(color == 'green'){
			colorCls = 'fr-bg-green';
		}
		if(color == 'red'){
			colorCls = 'fr-bg-red';
		}
		if(color == 'black'){
			colorCls = 'fr-bg-black';
		}
		return colorCls;
	};
	this.result = '';
	var _this = this;
	var flag = true;
	this.flicker = function(o, color){
		var fadeInColor  = this.getColor(color);
		var fadeOutColor = this.getColor();
		if(flag == true){
			$(o).attr('class', $(o).attr('class').replace(/fr\-bg\-\w+\s/ig, ''));
			flag = false;
		}
		_this.timer = setInterval(function(){
			if($(o).hasClass(fadeInColor)){
				$(o).removeClass(fadeInColor).addClass(fadeOutColor);
			}else{
				$(o).removeClass(fadeOutColor).addClass(fadeInColor);
			}
			if(stop){
				clearInterval(_this.timer);
				$(o).attr('class', $(o).attr('class').replace(/fr\-bg\-\w+\s*/ig, ''));
				$(o).addClass(_this.getColor(_this.result));
				stop = false;
			}
		}, 200);
	};
	this.stop = function(color){
		stop = true;
		this.result = color;
	}
}
var mobile_width = 640;
var bottomHeight = $('.fr-admin-bottom').height();
var headerHeight = $('.fr-admin-top').height();
var menuWidth = $('.fr-admin-menu').width();
//自适应高度
$(window).on('resize load', function(){
	var winHeight   = $('.fr-fullscreen').height();
	var winWidth    = $('.fr-fullscreen').width();
	if(mobile_width > winWidth){
		return;
	}
	var docHeight   = document.documentElement.clientHeight;
	$('.fr-admin-middle').height(docHeight - bottomHeight - headerHeight - 10);
	$('.fr-admin-main').width(winWidth - menuWidth - 30);
	var eles = ["fa-address-card-o", "fa-online", "fa-male", "fa-clock-o"];
	$('#status_bar>span>i.fa').each(function(idx){
		$(this).addClass(eles[idx]);
	})
})

$('.fr-menu').on('click', function(){
	$('<div class="fr-mask fr-fullscreen"></div>').appendTo($('body'));
	$('.fr-mask').show();
	$('.fr-admin-menu').show();
	$('.fr-mask').on('click', function(){
		$('.fr-admin-menu').hide();
		$(this).remove();
	})
})

initialize();